<?php

namespace app\index\controller;

use think\Db;
use think\Exception;

class Index
{
    private $_redis = null;
    private $_alidayu = null;

    public function __construct()
    {
        if ($this->_redis === null) $this->_redis = new \MyRedis();
        if ($this->_alidayu === null) $this->_alidayu = new \Alidayu();
    }

    /*
     * 定时任务队列
     * 8 0 * * * /usr/bin/php /home/wwwroot/homegarden/index.php Timer/Temp/reverse_sync_product
     * 10 0 * * * /usr/bin/php /home/wwwroot/api/public/index.php oa/Timing/run
     * * * * * * /usr/bin/php /home/wwwroot/api/public/index.php cms/Product/run
     * 9 0 * * * /usr/bin/php /home/wwwroot/api/public/index.php cms/Present/run
     * */
    public function index()
    {
        passthru('crontab -l');
    }

    /*
     * 发送取货信息
     * */
    public function sendPickUpMessage()
    {
        for ($i = 0; $i < 100; $i++) {
            $res = $this->sendMessage();
            if ($res != 'SUCCESS') break;
        }
    }

    public function sendMessage()
    {
        $msg = $this->_redis->getHandel()->lpop('msg');
        if ($msg) {
            $message = unserialize($msg);
            try {
                $resp = $this->_alidayu->pickup($message);
                $resp = json_decode(json_encode($resp), true);
                $message['code'] = isset($resp['result']) ? 0 : $resp['sub_code'];
                $message['msg'] = isset($resp['result']) ? '' : $resp['sub_msg'];
                $message['sendtime'] = date('Y-m-d H:i:s');
                Db::table('homegarden_oa.message')->insert($message);
            } catch (Exception $e) {
                return 'ERROR:' . $e->getMessage();
            }
            return 'SUCCESS';
        }
        return 'EMPTY';
    }

    /*
     * 抽取订单信息
     * */
    public function extractOrderInfo()
    {
        $time = time();
        $date = Date('Y-m-d', $time);
        $hour = Date('H', $time);
        if ($hour == '23') {
            $date = Date('Y-m-d', strtotime("$date +1 day"));
        }

        Db::startTrans();
        try {
            // 插入订单
            DB::execute(insertInfoSql($date, 2));
            DB::execute(insertBillSql($date, 2));
            DB::execute(insertDetailSql($date, 2));
            // 订单分品
            DB::execute(insertSiteProductSql($date));
            // 订单分包
            DB::execute(insertProductSql($date));
            // 更新采购需求
            DB::execute(insertPurchaseRequireSql($date));
            // 生成采购订单
            DB::execute(insertPurchaseSql($date));
            // 匹配服务人员
            DB::execute(updateWorkerWSql($date));
            DB::execute(updateWorkerXSql($date));
            DB::execute(updateWorkerYSql($date));
            DB::execute(updateWorkerZSql($date));
            DB::commit();
            return 'SUCCESS';
        } catch (Exception $e) {
            DB::rollback();
            return 'ERROR' . $e->getMessage();
        }
        return 'EMPTY';
    }

    /*
     * 同步商品信息
     * */
    public function syncProductInfo()
    {
        $date = Date('Y-m-d H:i:s', time());

        // 先执行下线操作
        $off_list = Db::table('homegarden_timer.product')->where('off_time', 'ELT', $date)
            ->where('off_status', 0)->column('id');

        // 后执行上线操作
        $on_list = DB::table('homegarden_timer.product')->where('on_time', 'ELT', $date)
            ->where('on_status', 0)->where('off_status', 0)->column('id');

        // 查询下线活动ID
        $off_buyGifts_list = DB::table('homegarden_timer.product')->alias('tp')
            ->join('homegarden_cms.product cp', 'cp.id = tp.id')
            ->where('tp.off_time', 'ELT', $date)
            ->where('tp.off_status', 0)
            ->where('cp.activity_id', 'neq', '')
            ->column('cp.activity_id');

        // 查询上线活动ID
        $on_buyGifts_list = DB::table('homegarden_timer.product')->alias('tp')
            ->join('homegarden_cms.product cp', 'cp.id = tp.id')
            ->where('tp.on_time', 'ELT', $date)
            ->where('tp.on_status', 0)
            ->where('cp.activity_id', 'neq', '')
            ->column('cp.activity_id');

        DB::startTrans();
        try {
            if ($off_list) $this->productOffLine($off_list);
            if ($on_list) $this->productOnLine($on_list);
            if ($off_buyGifts_list) $this->buyGiftsOffLine($off_buyGifts_list);
            if ($on_buyGifts_list) $this->buyGiftsOnLine($on_buyGifts_list);
            DB::commit();
            return 'SUCCESS';
        } catch (Exception $e) {
            DB::rollback();
            return 'ERROR' . $e->getMessage();
        }
        return 'EMPTY';
    }

    /*
     * 原商品同步，因加入买赠活动而整改停用
     * */
    public function _syncProductInfo()
    {
        $date = Date('Y-m-d H:i:s', time());

        // 先执行下线操作
        $off_list = Db::table('homegarden_timer.product')->where('off_time', 'ELT', $date)
            ->where('off_status', 0)->column('id');

        // 后执行上线操作
        $on_list = DB::table('homegarden_timer.product')->where('on_time', 'ELT', $date)
            ->where('on_status', 0)->where('off_status', 0)->column('id');
        Db::startTrans();
        try {
            if ($off_list) {
                // 更新homegarden.timer.product
                DB::table('homegarden_timer.product')->where('id', 'IN', $off_list)
                    ->update(['off_time' => date('Y-m-d H:i:s'), 'off_status' => '1']);
                // 更新homegarden_cms.product
                DB::table('homegarden_cms.product')->where('id', 'IN', $off_list)->setField('is_used', 2);
                // 更新homegarden.product
                DB::table('homegarden.product')->where('id', 'IN', $off_list)->setField('issale', 0);
                // 清空购物车
                $product_id = DB::table('homegarden_cms.product')->where('id', 'IN', $off_list)->column('code');
                DB::table('homegarden.shoppingcart')->where('product_id', 'IN', $product_id)->delete();
            }

            if ($on_list) {
                // 更新homegarden.timer.product
                DB::table('homegarden_timer.product')->where('id', 'IN', $on_list)
                    ->update(['on_time' => date('Y-m-d H:i:s'), 'on_status' => '1']);
                // 更新homegarden_cms.product
                DB::table('homegarden_cms.product')->where('id', 'IN', $on_list)
                    ->setField('is_used', 1);
                // 更新homegarden.product
                $sql = replaceProductByIds($on_list);
                DB::execute($sql);
            }

            DB::commit();
            return 'SUCCESS';
        } catch (Exception $e) {
            DB::rollback();
            return 'ERROR' . $e->getMessage();
        }
        return 'EMPTY';
    }

    /*
     * 产品上线操作
     * */
    public function productOnLine($off_list)
    {
        // 更新homegarden.timer.product
        DB::table('homegarden_timer.product')->where('id', 'IN', $off_list)
            ->update(['off_time' => date('Y-m-d H:i:s'), 'off_status' => '1']);
        // 更新homegarden_cms.product
        DB::table('homegarden_cms.product')->where('id', 'IN', $off_list)->setField('is_used', 2);
        // 更新homegarden.product
        DB::table('homegarden.product')->where('id', 'IN', $off_list)->setField('issale', 0);
        // 清空购物车
        $product_id = DB::table('homegarden_cms.product')->where('id', 'IN', $off_list)->column('code');
        DB::table('homegarden.shoppingcart')->where('product_id', 'IN', $product_id)->delete();
    }

    /*
     * 产品下线操作
     * */
    public function productOffLine($on_list)
    {
        // 更新homegarden.timer.product
        DB::table('homegarden_timer.product')->where('id', 'IN', $on_list)
            ->update(['on_time' => date('Y-m-d H:i:s'), 'on_status' => '1']);
        // 更新homegarden_cms.product
        DB::table('homegarden_cms.product')->where('id', 'IN', $on_list)
            ->setField('is_used', 1);
        // 更新homegarden.product
        $sql = replaceProductByIds($on_list);
        DB::execute($sql);
    }

    /*
     * 买赠活动上线操作
     * */
    public function buyGiftsOnLine($on_buyGifts_list)
    {
        $map['activity.id'] = ['in', $on_buyGifts_list];
        // 获得赠品信息
        $gifts = DB::table('homegarden_activity.buy_gifts')->alias('activity')
            ->join('homegarden_cms.product gift', 'gift.id = activity.gift_id', 'LEFT')
            ->where($map)->column('
                id,
                name product_name,
                brief_description product_briefDescription,
                number product_number,
                unit product_unit,
                category_class1 product_class1,
                category_class2 product_class2,
                category_class3 product_class3,
                thumb_image product_headImage,
                real_weight,
                1 is_gift
            ');
        // 更新
        DB::table('homegarden.product')->insertAll($gifts);

        // 获得活动信息
        $activity = DB::table('homegarden_activity.buy_gifts')->alias('activity')
            ->join('homegarden.product gift', 'gift.id = activity.gift_id', 'LEFT')
            ->where($map)->column("
                CONCAT('P', activity.id) active_id,
                gift.product_id,
                activity.buy,
                activity.gift
            ");
        // 更新
        DB::table('homegarden.present')->insertAll($activity);

        // 更新
        DB::table('homegarden_activity.buy_gifts')->where($map)->setField('is_used', 1);
    }

    /*
     * 买赠活动下线操作
     * */
    public function buyGiftsOffLine($off_buyGifts_list)
    {
        $map['activity.id'] = ['in', $off_buyGifts_list];
        // 删除赠品
        DB::table('homegarden.product')->alias('gift')
            ->join('homegarden_activity.buy_gifts activity', 'activity.gift_id = gift.id')
            ->where($map)->delete();

        // 删除已上线活动
        $where['active_id'] = ['in', array_map("getPresentID", $off_buyGifts_list)];
        DB::table('homegarden.present')->where($where)->delete();

        // 更新
        DB::table('homegarden_activity.buy_gifts')->where($map)->setField('is_used', 2);
    }

    /*
     * 同步赠品信息
     * 已停用，逻辑改为增加赠品时直接同步
     * */
    public function syncPresentInfo()
    {
        $present = DB::table('homegarden.present')->alias('activity')
            ->join('homegarden_cms.product pro', 'pro.activity_id = activity.active_id')
            ->join('homegarden_cms.product pre', 'pre.`code` = activity.product_id', 'LEFT')
            ->join('homegarden.product product', 'product.product_id = activity.product_id', 'LEFT')
//            ->where('pro.is_used', 1)
            ->where('pre.id', 'EXP', 'IS NULL')
            ->field('
                product.id,
                product.product_id `code`,
                product.product_name `name`,
                product.product_briefDescription brief_description,
                product.product_number number,
                product.product_unit unit,
                product.product_class1 category_class1,
                product.product_class2 category_class2,
                product.product_class3 category_class3,
                product.product_headImage thumb_image,
                product.real_weight,
                1 is_gift
            ')->select();
//        echo DB::table('homegarden.present')->getLastSql();

        if ($present) {
            DB::startTrans();
            try {
                DB::table('homegarden_cms.product')->insertAll($present);
                DB::commit();
                return 'SUCCESS';
            } catch (Exception $e) {
                DB::rollback();
                return 'ERROR' . $e->getMessage();
            }
        }
        return 'EMPTY';
    }

    /*
     * 每日统计
     * 用于统计报表数据查询
     * */
    public function dailyCount()
    {
        $user_login_count = DB::table('homegarden.user_info')->where("TO_DAYS(lastLoginTime) = TO_DAYS(CURDATE())")->count();
        $data = ['date' => date('Y-m-d'), 'user_login' => $user_login_count];

        $site_user_login_count = DB::table('homegarden.user_info')->alias('info')
            ->join('homegarden.user_address address', 'address.user_id = info.user_id')
            ->join('homegarden.vegetable_lng_lat site', 'site.entityaddressId = address.entityaddressId')
            ->where("TO_DAYS(lastLoginTime) = TO_DAYS(CURDATE())")->group('address.entityaddressId')
            ->field('CURDATE() date, address.entityaddressId site, count(*) user_login')->select();
        try {
            DB::table('daily_count')->insert($data);
            DB::table('daily_count')->insertAll($site_user_login_count);
        } catch (Exception $e) {
            return 'ERROR' . $e->getMessage();
        }
    }

    /*
     * 临时同步赠品信息
     * 已停用，逻辑改为增加赠品时直接同步
     * */
    public function tempPresentInfo()
    {
        $present = DB::table('homegarden.product')->alias('p')
            ->join('homegarden_cms.product cp', 'cp.`code` = p.product_id', 'LEFT')
            ->where('cp.id', 'EXP', 'IS NULL')
            ->field('
                p.id,
                p.product_id `code`,
                p.product_name `name`,
                p.product_briefDescription brief_description,
                p.product_number number,
                p.product_unit unit,
                p.product_class1 category_class1,
                p.product_class2 category_class2,
                p.product_class3 category_class3,
                p.product_headImage thumb_image,
                p.real_weight,
                1 is_gift
            ')->select();

        if ($present) {
            DB::startTrans();
            try {
                DB::table('homegarden_cms.product')->insertAll($present);
                DB::commit();
                return 'SUCCESS';
            } catch (Exception $e) {
                DB::rollback();
                return 'ERROR' . $e->getMessage();
            }
        }
        return 'EMPTY';
    }

    public function syncActivityInfo()
    {
        /*
         * 买赠活动
         * A 上架商品
         * 1. 查询活动id
         * 2. 同步赠品
         * 3. 同步活动
         * 4. 修改活动状态
         *
         * B 下架商品
         * 1. 查询活动id
         * 2. 删除赠品
         * 3. 修改活动状态
         * */

        $date = Date('Y-m-d H:i:s', time());
        // 查询活动ID
        $activity_id = DB::table('homegarden_timer.product')->alias('tp')
            ->join('homegarden_cms.product cp', 'cp.id = tp.id')
            ->where("tp.on_time) = TO_DAYS(CURDATE()) AND tp.on_status = 1 and cp.activity_id != ''")
            ->column('tp.id');
        $map['activity.id'] = ['in', $activity_id];
        print_r($map);

        // 获得赠品信息
        $gifts = DB::table('homegarden_activity.buy_gifts')->alias('activity')
            ->join('homegarden_cms.product gift', 'gift.id = activity.gift_id', 'LEFT')
            ->where($map)->column('
                id,
                name product_name,
                brief_description product_briefDescription,
                number product_number,
                unit product_unit,
                category_class1 product_class1,
                category_class2 product_class2,
                category_class3 product_class3,
                thumb_image product_headImage,
                real_weight,
                1 is_gift
            ');
        print_r($gifts);

        // 获得活动信息
        $activity = DB::table('homegarden_activity.buy_gifts')->alias('activity')
            ->join('homegarden.product gift', 'gift.id = activity.gift_id', 'LEFT')
            ->where($map)->column('
                activity.id active_id,
                gift.product_id,
                activity.buy,
                activity.gift
            ');
        print_r($activity);

        // 修改活动状态

        // 满减活动

        // 限购

        // 众筹

        // 任意付

    }

    /*
     * 手动发送优惠券
     * */
    public function sendCoupon()
    {
        $effectTime = date('Y-m-d');
        $send = DB::table('homegarden.help_send_coupon')->alias('send')
            ->join('homegarden.coupon coupon', 'coupon.coupon_Id = send.coupon_id', 'LEFT')
            ->where("TO_DAYS(date) = TO_DAYS(CURDATE()) and is_send = 0")
            ->column('send.id, send.user_id, send.coupon_id, coupon_validityDate date');
        foreach ($send as $k=>$u) {
            $ivalidityDate = intval($u['date']) - 1;
            $tmp = [
                'coupon_sn'=>time().str_pad(substr($k, -6), 6, '0', STR_PAD_LEFT),
                'coupon_id'=>$u['coupon_id'],
                'coupon_effectTime'=>$effectTime,
                'coupon_invalidTime'=>date('Y-m-d', strtotime("+$ivalidityDate day")),
                'coupon_status'=>0,
                'is_new' => 1,
                'user_id'=>$u['user_id'],
                'keyword'=>'manually'
            ];
            $dataList[intval($k/1000)][] = $tmp;
        }

        foreach ($dataList as $data){
            DB::table('homegarden.coupon_detail')->insertAll($data);
        }
        $map['id'] = ['in', array_column($send, 'id')];
        DB::table('homegarden.help_send_coupon')->where($map)->setField('is_send', 1);
    }

}
